import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_fronter_service/controller/UpdateController.dart';
import 'package:flutter_fronter_service/model/address_entity.dart';
import 'package:flutter_fronter_service/tools/commons.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:get/get.dart';

import '../api/addressApi.dart';
class AddressDetail extends StatefulWidget {

  late bool isEdit;

  AddressDetail({Key? key, required this.isEdit}) : super(key: key);

  @override
  State<AddressDetail> createState() => _AddressDetailState();
}

class _AddressDetailState extends State<AddressDetail>{
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _addressController = TextEditingController();
  final UpdateController controller = Get.put(UpdateController());
  late AddressEntity addressEntity;

  int _gender = 1; // 默认男性为1
  bool _isDefaultAddress = false;
  bool isLoading = true;  // 是否正在加载
  String initProvince = '云南省', initCity = '昆明市', initTown = '呈贡区';


  @override
  void initState() {
    super.initState();
    _initAddress();
  }

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    _addressController.dispose();
    super.dispose();
  }

  Future<void> _initAddress () async{
    String? name = Get.rawRoute?.settings.name;
    if( name!.contains("save")){
      print("save");
      //路径含save说明为保存地址
      addressEntity = AddressEntity();
      addressEntity.province = initProvince;
      addressEntity.city = initCity;
      addressEntity.district = initTown;
    }else if(name.contains("edit")){
      //获取参数id
      var res = await getByIdApi(Get.arguments["id"]);
      addressEntity = AddressEntity.fromJson(res["data"]);
      _nameController.value =
          TextEditingValue(text: addressEntity.contactName);
      _phoneController.value =
          TextEditingValue(text: addressEntity.contactTel);
      _addressController.value =
          TextEditingValue(text: addressEntity.address);
      _gender = addressEntity.contactSex;

    }
    if (!addressEntity.isNull) {
      isLoading = false;  // 数据加载完毕，更新加载状态
    }
    setState(() {
    });
  }

  void _submitForm() async{
    if (_formKey.currentState!.validate()) {
      // 处理提交逻辑
      addressEntity.contactName = _nameController.text;
      addressEntity.contactTel = _phoneController.text;
      addressEntity.address = _addressController.text;
      addressEntity.contactSex = _gender;
      // addressEntity.defaultAddress = _isDefaultAddress;
      await saveAddressApi(addressEntity);
      Get.back(result: true);
    }else{
      CommonUtils.showToast("请填写完整信息");
    }
  }

  Widget _checkLocation() {
    return InkWell(
        onTap: () {
          Pickers.showAddressPicker(
            context,
            initProvince: addressEntity.province,
            initCity: addressEntity.city,
            initTown:  addressEntity.district,
            onConfirm: (p, c, t) {
              setState(() {
                addressEntity.province = p;
                addressEntity.city = c;
                addressEntity.district = t!;
              });
            },
          );
        },
        child: Text('${ addressEntity.province} - ${addressEntity.city}- ${addressEntity.district}'));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: !widget.isEdit?Text('添加'):Text('编辑'),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: isLoading ? Center(child: CircularProgressIndicator()) : Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(labelText: '收货人'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入收货人姓名';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16),
              TextFormField(
                controller: _phoneController,
                decoration: InputDecoration(labelText: '手机号'),
                keyboardType: TextInputType.phone,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入手机号';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16),
              Row(
                children: [
                  Text('性别:'),
                  Expanded(
                    child: RadioListTile<int>(
                      title: Text('男'),
                      value: 1,
                      groupValue: _gender,
                      onChanged: (value) {
                        setState(() {
                          _gender = value!;
                        });
                      },
                    ),
                  ),
                  Expanded(
                    child: RadioListTile<int>(
                      title: Text('女'),
                      value: 0,
                      groupValue: _gender,
                      onChanged: (value) {
                        setState(() {
                          _gender = value!;
                        });
                      },
                    ),
                  ),
                ],
              ),
              SizedBox(height: 16),
              Container(
                child: Row(
                  children: [
                    Text("地址："),
                    _checkLocation(),
                  ],
                ),
              ),
              TextFormField(
                controller: _addressController,
                decoration: InputDecoration(labelText: '详细地址'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入地址';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('是否为默认地址'),
                  Switch(
                    value: addressEntity.defaultAddress,
                    onChanged: (value) {
                      setState(() {
                        addressEntity.defaultAddress = value;
                      });
                    },
                  ),
                ],
              ),
              SizedBox(height: 16),
              ElevatedButton(
                onPressed: _submitForm,
                child: Text('提交'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
